package com.wocai.jrt.orgadmin.employee.action;

import java.util.List;

import javax.inject.Inject;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.vteba.utils.id.ObjectId;
import com.vteba.web.action.GenericAction;
import com.vteba.web.action.JsonBean;
import com.wocai.jrt.orgadmin.employee.bean.EmployeeGroupReqBean;
import com.wocai.jrt.orgadmin.employee.model.EmployeeGroup;
import com.wocai.jrt.orgadmin.employee.model.GroupMember;
import com.wocai.jrt.orgadmin.employee.service.spi.EmployeeGroupService;
import com.wocai.jrt.orgadmin.employee.service.spi.GroupMemberService;
import com.wocai.jrt.orgadmin.utils.UserUtils;

/**
 * 理财团队控制器
 * 
 * @author yinlei
 * @date 2015-8-4 15:49:29
 */
@Controller
@RequestMapping("/employeeGroup")
public class EmployeeGroupAction extends GenericAction<EmployeeGroup> {
	private static final Logger LOGGER = LoggerFactory.getLogger(EmployeeGroupAction.class);

	@Inject
	private EmployeeGroupService employeeGroupServiceImpl;
	@Inject
	private GroupMemberService groupMemberServiceImpl;
	
	/**
	 * 根据Id获得理财团队实体，Json格式。
	 * 
	 * @param id
	 *            参数id
	 * @return 理财团队实体
	 */
	@ResponseBody
	@RequestMapping("/get")
	public JsonBean get(String id) {
		JsonBean json = new JsonBean();
		try {
			EmployeeGroup model = employeeGroupServiceImpl.get(id);
			if (null == model) {
				json.setCode(0);
				json.setMessage(ERROR);
				return json;
			}
			json.setCode(1);
			json.setData(model);
		} catch (Exception e) {
			json.setCode(0);
			json.setMessage(ERROR);
			LOGGER.error("get record error, errorMsg=[{}].", e.getMessage());
		}
		return json;
	}

	/**
	 * 执行实际的新增操作
	 * 
	 * @param model
	 *            要新增的数据
	 * @return 新增页面逻辑视图
	 */
	@ResponseBody
	@RequestMapping("/doAdd")
	public JsonBean doAdd(EmployeeGroupReqBean model) {
		JsonBean bean = new JsonBean();
		if (StringUtils.isAnyBlank(model.getGroupName(), model.getParent())) {
			bean.setCode(0);
			bean.setMessage("请输入部门完整信息");
			return bean;
		}
		if (model.getGroupName().length()>40) {
			bean.setCode(0);
			bean.setMessage("部门名称太长了，请输入少于40个字符");
			return bean;
		}
		try {
			EmployeeGroup parentGroup = employeeGroupServiceImpl.get(model.getParent());
			if (null == parentGroup) {
				bean.setCode(0);
				bean.setMessage("父节点不存在");
				return bean;
			}
			if (parentGroup.getPlannerGroup()) {
				bean.setCode(0);
				bean.setMessage("理财师部门下面不能挂部门");
				return bean;
			}
			EmployeeGroup queryGroup = new EmployeeGroup();
			queryGroup.setParent(model.getParent());
			queryGroup.setDeleted(false);
			List<EmployeeGroup> employeeGroupList = employeeGroupServiceImpl.queryList(queryGroup);
			for (EmployeeGroup employeeGroup : employeeGroupList) {
				if (model.getGroupName().equals(employeeGroup.getGroupName())) {
					bean.setCode(0);
					bean.setMessage("该节点存在相同名称的部门！");
					return bean;
				}
			}
			// int result = employeeGroupServiceImpl.addGroup(model);
			EmployeeGroup employeeGroup = new EmployeeGroup();
			employeeGroup.setId(ObjectId.get().toString());
			employeeGroup.setGroupName(model.getGroupName());
			employeeGroup.setParent(model.getParent());
			employeeGroup.setMemberNumber(0);
			employeeGroup.setDeleted(false);
			employeeGroup.setInvestorNumber(0);
			employeeGroup.setOrgId(UserUtils.getOrgId());
			employeeGroup.setPlannerGroup(model.getPlannerGroup());
			employeeGroup.setProductNumber(0);
			employeeGroup.setSaleAll(false);
			int result = employeeGroupServiceImpl.save(employeeGroup);
			if (result == 1) {
				bean.setMessage(SUCCESS);
				bean.setCode(1);
				LOGGER.info("save record success.");
			} else {
				bean.setCode(0);
				bean.setMessage(ERROR);
				LOGGER.error("save record error.");
			}
		} catch (Exception e) {
			LOGGER.error("save record error, errorMsg=[{}].", e.getMessage());
			bean.setCode(0);
			bean.setMessage(ERROR);
		}
		return bean;
	}

	/**
	 * 更新理财团队信息
	 * 
	 * @param model
	 *            要更新的理财团队信息，含有ID
	 * @return 操作结果信息
	 */
	@ResponseBody
	@RequestMapping("/update")
	public JsonBean update(EmployeeGroupReqBean model) {
		JsonBean bean = new JsonBean();
		if (StringUtils.isAnyBlank(model.getGroupName(), model.getGroupId())) {
			bean.setCode(0);
			bean.setMessage("参数不完整！");
			return bean;
		}
		try {
			if (model.getPlannerGroup()) {
				EmployeeGroup employeeGroup = new EmployeeGroup();
				employeeGroup.setParent(model.getGroupId());
				employeeGroup.setDeleted(false);
				List<EmployeeGroup> employeeGroupList = employeeGroupServiceImpl
						.queryList(employeeGroup);
				if (employeeGroupList.size() > 0) {
					bean.setCode(0);
					bean.setMessage("该部门下还有其他部门，不能修改为理财师部门！");
					return bean;
				}
			}
			EmployeeGroup employeeGroup = new EmployeeGroup();
			employeeGroup.setId(model.getGroupId());
			employeeGroup.setGroupName(model.getGroupName());
			employeeGroup.setPlannerGroup(model.getPlannerGroup());
			int result = employeeGroupServiceImpl.updateEmpGroupById(employeeGroup);
			if (result == 1) {
				bean.setCode(1);
				bean.setMessage(SUCCESS);
			} else {
				bean.setCode(0);
				bean.setMessage(SUCCESS);
			}
		} catch (Exception e) {
			LOGGER.error("update record error, errorMsg=[{}].", e.getMessage());
			bean.setCode(0);
			bean.setMessage(ERROR);
		}
		return bean;
	}

	/**
	 * 删除理财团队信息
	 * 
	 * @param id
	 *            要删除的理财团队ID
	 */
	@ResponseBody
	@RequestMapping("/delete")
	public JsonBean delete(String groupId) {
		JsonBean json = new JsonBean();
		try {
			// int result = employeeGroupServiceImpl.deleteGroup(groupId);
			GroupMember groupMember = new GroupMember();
			groupMember.setGroupId(groupId);
			List<GroupMember> groupMemberList = groupMemberServiceImpl.queryList(groupMember);
			if (groupMemberList.size() > 0) {
				json.setCode(0);
				json.setMessage("团队下还有员工，不能删除！");
				return json;
			}
			EmployeeGroup employeeGroup = new EmployeeGroup();
			employeeGroup.setParent(groupId);
			employeeGroup.setDeleted(false);
			List<EmployeeGroup> employeeGroupList = employeeGroupServiceImpl
					.queryList(employeeGroup);
			if (employeeGroupList.size() > 0) {
				json.setCode(0);
				json.setMessage("团队下还有团队，不能删除！");
				return json;
			}

			EmployeeGroup employeeGroupUpdata = new EmployeeGroup();
			employeeGroupUpdata.setId(groupId);
			employeeGroupUpdata.setDeleted(true);
			int result = employeeGroupServiceImpl.updateById(employeeGroupUpdata);
			if (result == 1) {
				json.setMessage(SUCCESS);
				json.setCode(1);
				LOGGER.info("delete record success, id=[{}].", groupId);
			} else {
				json.setMessage(ERROR);
				LOGGER.error("delete record error.");
			}
		} catch (Exception e) {
			LOGGER.error("delete record error, id=[{}], errorMsg=[{}].", groupId, e.getMessage());
			json.setMessage(ERROR);
		}
		return json;
	}

//	/**
//	 * 查询机构下可用的理财师（不是部门负责人）。
//	 * 
//	 * @param employeeKey
//	 * @return List<EmpBreifBean>
//	 */
//	@ResponseBody
//	@RequestMapping("/employee/{employeeKey}")
//	public JsonBean employee(@PathVariable("employeeKey") String employeeKey) {
//		JsonBean bean = new JsonBean();
//		try {
//			List<EmpBreifBean> eBean = employeeGroupServiceImpl.getEmployeeNotGroup(employeeKey);
//			bean.setCode(1);
//			bean.setData(eBean);
//		} catch (Exception e) {
//			bean.setCode(0);
//			bean.setMessage("获取理财师列表失败");
//			LOGGER.error("get employee list error, errorMsg=[{}].", e.getMessage());
//		}
//		return bean;
//	}

	/**
	 * 检查该部门能不能添加部门
	 * 
	 * @param employeeKey
	 * @return List<EmpBreifBean>
	 */
	@ResponseBody
	@RequestMapping("/checkGroupId")
	public JsonBean checkGroupId(String groupId) {
		JsonBean bean = new JsonBean();
		try {
			EmployeeGroup employeeGroup = employeeGroupServiceImpl.get(groupId);
			if (employeeGroup == null) {
				bean.setCode(0);
				bean.setMessage("部门不存在");
				return bean;
			}
			if (employeeGroup.getPlannerGroup()) {
				bean.setCode(0);
				bean.setMessage("理财师部门下不能挂部门");
				return bean;
			}
			bean.setMessage(SUCCESS);
			bean.setCode(1);
		} catch (Exception e) {
			bean.setCode(0);
			bean.setMessage("服务器出了点小问题，请稍后重试！");
			LOGGER.error("check groupId error, errorMsg=[{}].", e.getMessage());
		}
		return bean;
	}
}
